<template>
  <div class="search-suggestion">
    <van-cell v-for="(text, index) in searchList" :key="index" icon="search" @click="$emit('search', text)">
      <div slot="title" v-html="highLight(text)"></div>
    </van-cell>
   </div>
</template>

<script>
import { getSearchSuggestions } from '@/api/search'
import { debounce } from "lodash"
export default {
  name: 'SearchSuggestion',
  components: {},
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      searchList: [] // 搜索联想建议列表
    }
  },
  computed: {},
  watch: {
    searchText: {
      // handler (value) {
      //   console.log(value)
      //   this.getSearchSuggestions(value)
      // },
      // 处理防抖
      handler: debounce(function (value) {
        this.getSearchSuggestions(value)
      }, 300),
      immediate: true
    }
  },
  created () {},
  mounted () {},
  methods: {
    async getSearchSuggestions (q) {
      try {
        const { data } = await getSearchSuggestions(q)
        console.log(data)
        this.searchList = data.data.options
      } catch (error) {
        this.$toast('数据获取失败，请稍后再试')
      }
    },
    highLight (text) {
      const highLightStr = `<span style="color: #3296fa">${this.searchText}</span>`
      const reg = new RegExp(this.searchText, 'gi')
      return text.replace(reg, highLightStr)
    }
  }
}
</script>

<style scoped lang="less"></style>
